package com.szmg.wishwalls.dao.impl;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.szmg.wishwalls.dao.MenuDao;
import com.szmg.wishwalls.model.Menu;

@Repository("menuDao")
public class MenuDaoImpl implements MenuDao{
	@Resource(name="hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	
	public List<Menu> queryProgramBaseMenu(String programCode){
		StringBuilder sb = new StringBuilder();
		sb.append("	FROM Menu m ");
		sb.append("	WHERE");
		sb.append("	EXISTS(");
		sb.append("		SELECT 1");
		sb.append("		FROM Production p");
		sb.append("		WHERE");
		sb.append("			EXISTS(");
		sb.append("				SELECT 1");
		sb.append("				FROM ProgramProductionRelation pr");
		sb.append("				WHERE pr.productionId = p.id");
		sb.append("				AND EXISTS(");
		sb.append("					SELECT 1");
		sb.append("					FROM Program pg");
		sb.append("					WHERE pg.code = ?");
		sb.append("					AND pg.id = pr.programId");
		sb.append("					AND curdate() BETWEEN pg.startDate and pg.endDate");
		sb.append("					)");
		sb.append("			)");
		sb.append("			AND p.menuBaseId = m.id");
		sb.append("	)");
		List<Menu> list = hibernateTemplate.find(sb.toString(),new Object[]{programCode});
		if(CollectionUtils.isEmpty(list)) return Collections.emptyList();
		return list;
	}
	
	public List<Menu> queryMenuByParentId(String programCode,String parentId){
		StringBuilder sb = new StringBuilder();
		sb.append("	FROM Menu m ");
		sb.append("	WHERE");
		sb.append("	EXISTS(");
		sb.append("		SELECT 1");
		sb.append("		FROM Production p");
		sb.append("		WHERE");
		sb.append("			EXISTS(");
		sb.append("				SELECT 1");
		sb.append("				FROM ProgramProductionRelation pr");
		sb.append("				WHERE pr.productionId = p.id");
		sb.append("				AND EXISTS(");
		sb.append("					SELECT 1");
		sb.append("					FROM Program pg");
		sb.append("					WHERE pg.code = ?");
		sb.append("					AND pg.id = pr.programId");
		sb.append("					AND curdate() BETWEEN pg.startDate and pg.endDate");
		sb.append("					)");
		sb.append("			)");
		sb.append("			AND p.menuLeafId = m.id");
		sb.append("	)");
		sb.append(" and m.parentId = ?");
		List<Menu> list = hibernateTemplate.find(sb.toString(),new Object[]{programCode,parentId});
		if(CollectionUtils.isEmpty(list)) return Collections.emptyList();
		return list;
	}
}
